// pages/connect/connect.js

const app = getApp()

let { downFile } = require("./upload.js");
var WCHBLEWxJsLib = require('../../utils/WCHBLEWxJsLib.js');

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollViewHeight:50,
    deviceId:null,
    name:'',
    chs:[],
    connected: false,
    openBlueFlag:false,
     // 接收
     rate:0,
     newVal:'',
     newValLength:0,
     oldValLength:0,
    //  timer:null, //计速度
     count:0,
     openHexFlag1:false,
     // 发送
     rate2:0,
     sendValue:null,
     openHexFlag:false,
     newSendLength:0,
     oldSendLength:0,
     count2:0,
     modalName:'',
     arrow:'/pages/assets/img/arrow_btm.png',
     flow:'关',//流控
     currentBTL2:115200,
     currentJYW2:0,
     currentTZW2:1,
     currentSJW2: 8,
     checkBtn2:[{value:'DTR'},{value:'RTS'}],
     checkedValue2:['DTR','RTS'],

    // 波特率
      isShowBTL: false,
      currentBTL: 115200,
      arr1:[1200,2400,4800,9600,19200,38400,57600,115200, 230400,1000000],

      // 数据位
      isShowSJW: false,
      currentSJW: 8,
      arr2:[5,6,7,8],
       // 停止位
       isShowTZW: false,
       currentTZW: 1,
       arr3:[1,2],
        // 校验位
        isShowJYW: false,
        currentJYWname: '无',
        currentJYW:0,//
        arr4:[
          {name:'无',value:0},
          {name:'奇校验',value:1},
          {name:'偶校验',value:2},
          {name:'标志位',value:3},
          {name:'空白位',value:4},
         ],
        // 流控
        openRTSBtn:false,
        checkBtn:[{value:'DTR'},{value:'RTS'}],
        checkedValue:['DTR','RTS'],
        checkStatus:false,//RTS是否被选中
        // :false,
        radioStr:'单次发送',//选择的发送方式
        sendTypeArr:[{name:'single',value:'单次发送',checked:true},
        {name:'timer',value:'定时发送'},
      ],
        sendTime:null,//时间间隔
        realSendTime:null,
        sendType:'单次发送',//确定发送的方式
        sendFlag:true,
        contentValue:null,
        reciveTypeArr:[
          {name:'实时显示,不会自动清空',value:'1'},
        {name:'实时显示,当内容长度超过1500字符时暂停',value:'2'},
        {name:'实时显示,当内容长度超过1500字符时自动清空',value:'3',checked:true},
        ],
        checkedreciveValue:'3',
        checkedreciveValue2:'3',//确定的
        editMtu:null,
        reditMtu:23,
        isPopping:false,
        mtuValue:null

  },

  /**
   * 生命周期函数--监听页面加载
   */

  //  操作
  // 串口参数
  changeBtn(e){
    this.setData({
      checkedValue:e.detail.value
    })
    if(this.data.checkedValue.indexOf('RTS')=='-1'){
      this.setData({
        checkStatus:false
      })
    }else{
      this.setData({
        checkStatus:true
      })
    }
    this.setValueModem()
  },
  changeRTSBtn(e){
   this.setData({
    openRTSBtn:e.detail.value,
   })
   this.setValueModem()
  },
  showModal(e) {
    if(e.currentTarget.dataset.num==1){//设置串口
      var checkBtn2=this.data.checkBtn2
      var checkJYWArr=this.data.arr4
      var name=this.data.currentJYWname

      checkJYWArr.forEach((item,index) => {

        if(this.data.currentJYW2==index){
          item.checked=true
           name =item.name
        }else{
          item.checked=false
        }
      });

      checkBtn2.forEach(item => {
        if(this.data.checkedValue2.indexOf(item.value)>=0){
          item.checked=true
        }else{
          item.checked=false
        }
      });


      this.setData({
        currentBTL:this.data.currentBTL2,
        currentSJW:this.data.currentSJW2,
        currentTZW:this.data.currentTZW2,
        currentJYW:this.data.currentJYW2,
        openRTSBtn :this.data.flow=='开'?true:false,
        checkBtn:this.data.checkBtn2,
        checkedValue:this.data.checkedValue2,
        arr4:checkJYWArr,
        currentJYWname:name
      })
    }
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  
  validateNumber(val) {
    var partern=/^[0-9]*$/
    var reg = new RegExp(partern)
    return reg.test(val)
  },

  // 输入间隔
  inputVlaue(e) {
   
    var val= this.validateNumber(e.detail.value)
 
   if(!val){
     wx.showToast({
       title: '只能输入数字',
       icon:'none'
     })
     this.setData({
       sendTime:e.detail.value.replace(/\D/g, '')
     })
 
   }else{
       var type = e.currentTarget.dataset.type
       this.setData({
         [type]: e.detail.value
       })
   }
   },

// 配送方式
  submitSend(e){
    if(this.data.radioStr=='定时发送'&&this.data.sendTime<40){
      wx.showToast({
        title: '输入的值不小于40',
        icon:'none'
      })
    }else{
      if(this.data.radioStr=='定时发送'){
        this.setData({
          realSendTime:this.data.sendTime
        })
      }else{
        this.setData({
          realSendTime:null
        }) 
      }
      this.setData({
        sendType:this.data.radioStr,
        modalName: null,
      })
       wx.showToast({
        title: '配置成功',
       })
      this.clearData()
    }
  },

  clearData(){
    let data=this.data.sendTypeArr
    data.forEach(item => {
      if(item.value==this.data.sendType){
        item.checked=true
      }else{
        item.checked=false
      }
    });
     this.setData({
      radioStr:this.data.sendType,
      sendTypeArr:data,
      sendTime:this.data.realSendTime
     })
  },

  hideBox(){

  },
  hideModal(e) {
    this.setData({
      modalName: null,
    })
    if(e.currentTarget.dataset.type==2){
      this.clearData()
    }
  },
  optionTap(e) {
    let index=e.currentTarget.dataset.type
    let item=e.currentTarget.dataset.item
    if(index==1){
      this.setData({
        isShowBTL: false,
        currentBTL:item ,
      });
    }else if(index==2){
      this.setData({
        isShowSJW: false,
        currentSJW:item,
      });
    }else if(index==3){
      this.setData({
        isShowTZW: false,
        currentTZW: item,
      });
    }else  if(index==4){
      this.setData({
        isShowJYW: false,
        currentJYWname: item.name,
        currentJYW:item.value
      });
    }
  },
  openCloseStore(e) {
    let index=e.currentTarget.dataset.type
    if(index==1){
      this.setData({
        isShowBTL: !this.data.isShowBTL
      })
      if(this.data.isShowBTL){
        this.setData({
          isShowSJW:false,
          isShowTZW:false,
          isShowJYW:false,
        })
      }

    }else if(index==2){
      this.setData({
        isShowSJW: !this.data.isShowSJW
      })
      if(this.data.isShowSJW){
        this.setData({
          isShowBTL:false,
          isShowTZW:false,
          isShowJYW:false,
        })
      }

    }else if(index==3){
      this.setData({
        isShowTZW: !this.data.isShowTZW
      })
      if(this.data.isShowTZW){
        this.setData({
          isShowBTL:false,
          isShowSJW:false,
          isShowJYW:false,

        })
      }
    }else if(index==4){
      this.setData({
        isShowJYW: !this.data.isShowJYW
      })
      if(this.data.isShowJYW){
        this.setData({
          isShowBTL:false,
          isShowSJW:false,
          isShowTZW:false,
          

        })
      }
    }
  },
  // 接收方式
  radioChange2: function (e) {
    var str = null;
    // console.log(e.detail,'detail')
    for (var value of this.data.reciveTypeArr) {
     if (value.value == e.detail.value) {
      str = value.value;
      break;
     }
    }
    this.setData({ checkedreciveValue: str });
  },

  hideModal3(){

    let data=this.data.reciveTypeArr
    data.forEach(item => {
      if(item.value==this.data.checkedreciveValue2){
        item.checked=true
      }else{
        item.checked=false
      }
    });
   
     this.setData({
      checkedreciveValue:this.data.checkedreciveValue2,
      reciveTypeArr:data,
      modalName: null,
     })

  },
  submitSend3(){
    this.setData({
      checkedreciveValue2:this.data.checkedreciveValue,
      modalName: null,
      
    })

  },
  // 发送方式
  radioChange: function (e) {
    var str = null;
    for (var value of this.data.sendTypeArr) {
     if (value.name === e.detail.value) {
      str = value.value;
      break;
     }
    }
    this.setData({ radioStr: str });
   },
// 随机数
  randomString(n) {  
    let str = '9876543210';
    let tmp = '',
        i = 0,
        l = str.length;
    for (i = 0; i < n; i++) {
      tmp += str.charAt(Math.floor(Math.random() * l));
    }
    return tmp;
  },
  onLoad: function (options) {
  
    wx.setNavigationBarTitle({
      title:options.name?options.name:'连接蓝牙'
    })
    this.setData({
      deviceId: options.deviceId,
      name:options.name,
      connected:true,
       rate:0,
       newVal:'',
       newValLength:0,
       oldValLength:0,
       rate2:0,
       newSendLength:0,
       oldSendLength:0,
       count2:0,
      
    })
    
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight
        });
      }
    });
    let query = wx.createSelectorQuery().in(this);
    query.select('#firstPart').boundingClientRect();
    query.select('#secondPart').boundingClientRect();
    query.select('#forthPart').boundingClientRect();
    query.select('#fivePart').boundingClientRect();
    query.exec((res) => {
      let firstPartHeight = res[0].height;
      let secondPartHeight = res[1].height;
      let forthPartHeight = res[2].height;
      let fivePartPartHeight = res[3].height;
      let scrollViewHeight = this.data.windowHeight - firstPartHeight-secondPartHeight-forthPartHeight-fivePartPartHeight
      this.setData({
        scrollViewHeight: scrollViewHeight
      });
    });
   
   if(options.deviceId){
     this.getBLEDeviceServices(options.deviceId)
   }
   
  },
  closeBox(){
    if(this.data.isPopping){
      this.selectComponent("#popup").plus(1)
    }
  
  },
  // 更多
  menuItemClick:function(res){
    //获取点击事件的信息
    let clickInfo = res.detail.iteminfo 
    if(clickInfo=='editMtu'){
      this.setData({
        modalName:"MTUBOX" 
      })
    }else if(clickInfo=='aboutUs'){
      console.log(clickInfo,'clickInfo')
      this.setData({
        modalName:"aboutUS" 
      })
    }
    this.setData({
      isPopping: res.detail.isPopping
      })
  },
  inputMtu(e){
    this.setData({
      editMtu:e.detail.value,
    })
  },
  submitSendMtu(){
    WCHBLEWxJsLib.setMTU(this.data.editMtu,this.data.deviceId,this).then((res)=>{
      wx.showToast({
        title: res.message,
        icon:'none'
      })
      console.log(res)
    }).catch(err=>{
      wx.showToast({
        title: err.message,
        icon:'none'
      })
      console.log(err)
    })
  },


  copyWord(){
    wx.setClipboardData({
      data: 'http://wch.cn/',
      success: function (res) {
          wx.getClipboardData({ 
            success: function (res) {
             }
            })
          }          
      })
  },
  hideModalAboutUs(){
    this.setData({
      modalName: null,
    })
  },
  hideModalMtu(){
    this.setData({
      modalName: null,
      editMtu:null
    })
  },

  sendValueCircle(){
    var num=this.randomString(180)
    this.setData({
      sendValue:num
    })
    this.countNum()
  },

  readBLECharacteristicValue(deviceId,serviceId,id){
    wx.readBLECharacteristicValue({
      deviceId,
      serviceId,
      characteristicId: id,
      success: function (res) {
           console.log('读取成功',res)
       },
       fail: function (res) {
        console.log('读取失败',res)
      }
    })
  },
  
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          console.log(res.services)

          if (res.services[i].uuid.indexOf('FFF0')>0) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  // 获取蓝牙设备某个服务中所有特征值
   getBLEDeviceCharacteristics(deviceId, serviceId) {
     //监听和获取串口配置信息及Modem状态
    WCHBLEWxJsLib.getSerialModemCharacteristics(deviceId, serviceId,this).then(res=>{
      wx.showToast({
        title: res.message,
        icon:'none',
        duration: 2000,
      })
      console.log(res)
    }).catch(err=>{
      wx.showToast({
        title: err.message,
        icon:'none',
        duration: 2000,
      })
      console.log(err)
    })
    var that=this
    wx.onBLEConnectionStateChange(function(res){
      if(!res.connected){
        wx.showToast({
          title: '蓝牙连接已断开',
          icon:'none',
          duration: 2000,
        })
        if(that.data.connected){
          that.closeBLEConnection()
          that.setData({
            connected:false
          })
        }
      }
      // console.log("蓝牙设备连接状态监听回调：\n"+JSON.stringify(res));
    });

    // 操作之前先监听，保证第一时间获取数据
    WCHBLEWxJsLib.receiveBLECharacteristicValue(this).then(res=>{
      console.log(res)
    }).catch(error=>{
      console.log(error)
    })
  },

  closeBLEConnection(num) {
    if(this.data.connected){
      this.setData({
        connected: false,
        chs: [],
        canWrite: false,
      })
      wx.closeBLEConnection({
        deviceId: this.data.deviceId
      })
     
      wx.showToast({
        title: '连接已断开',
        icon: 'none'
      });
  
      this.closeBluetoothAdapter()
      if(num){
        this.clearInterval()
        wx.navigateTo({
          url: '../listPage/index',
        })
      }

    }
   
  },

  // 停止发送
  stopSendValue(){
    this.setData({
      sendFlag:true
    })
    clearInterval(app.globalData.sendTimer)
  },
  // 定时发送
  circleSendValue(value,flag){
    app.globalData.sendTimer=setInterval(() => {
      let count=this.data.reditMtu-3
      let source=value
      let that=this
      for (let i = 0, len = source.length / count; i < len; i++) {
        let subStr = source.substr(0, count);
        let length= this.countValueLength(subStr.length,flag)
        setTimeout(()=>{

          if(!that.data.openHexFlag){
            that.handleSendvalue(that.stringToArrayBuffer(subStr),3, that._deviceId,that._serviceId,that._characteristicId,length )
          }else{
            that.handleSendvalue(that.string2buffer(subStr),3, that._deviceId,that._serviceId,that._characteristicId,length )
          }
        },1000)
        source = source.replace(subStr, "");
      }
     },this.data.realSendTime);
  },

      /**
  * 将字符串转换成ArrayBufer
  */
     // 传送10进制
     stringToArrayBuffer(str) {
      if (!str) {
      return new ArrayBuffer(0);
      }
      var buffer = new ArrayBuffer(str.length);
      let dataView = new DataView(buffer)
      let ind = 0;
      for (var i = 0, len = str.length; i < len; i += 1) {
        var s=str.charCodeAt(i)
        let code = str.substr(i, 1)
        //  console.log(ind,s,'10进制')
         dataView.setUint8(ind, s)
         ind++
      }
      console.log(buffer,'buffer')
      return buffer;
     },
  // 传输16进制
  string2buffer(str) {
      let val = ""
      if(!str) return;
      let length = str.length;
      let index = 0;
      let array = []
      while(index < length){
        array.push(str.substring(index,index+2));
        index = index + 2;
      }
      val = array.join(",");
      // 将16进制转化为ArrayBuffer
      return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)//16进制转为10进制
      })).buffer
    },

  // 计算长度
countValueLength(val,flag){
    if(flag){
      return val/2
    }else{
      return val
    }
},

  //断连
  clickClose(){
    WCHBLEWxJsLib.disconnectBLEDevice(1,this.data.connected,this.data.deviceId,this).then(res=>{
      console.log(res)
    }).catch(err=>{
      console.log(err)
    })
  },

  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
    this.setData({
      openBlueFlag:false
    })
    // console.log('关闭进程connect')
  },
 
  countNum(){
      if(this.data.openHexFlag){
        this.setData({
          count2:this.data.sendValue.length/2
        })
      }else{
        this.setData({
          count2:this.data.sendValue.length
        })
      }
  },

  formSubmit(e){
    this.setData({
      sendValue:e.detail.value.sendValue
    })
    WCHBLEWxJsLib.writeToPeripheral(this).then(res=>{
      console.log(res)
    }).catch(err=>{
      wx.showToast({
        title: err.message,
        icon:'none'
      })
    })
  },

  changeFlag1(e){
      let type=e.currentTarget.dataset.type
      let value=e.detail.value
      this.setData({
        openHexFlag1:value,
      })
  },
  changeFlag2(e){
    let type=e.currentTarget.dataset.type
    let value=e.detail.value
    this.setData({
      openHexFlag:value,
     })

     if(value){
      this.setData({
        count2:this.data.sendValue.length/2
       })
    }else{
      this.setData({
        count2:this.data.sendValue.length
       })
    }

  },
  // 清空
  clearBtn(e){
    var num= e.currentTarget.dataset.num
    if(num==1){
      this.setData({
        rate:0,
        newValLength:0,
        oldValLength:0,
        newVal:'',
      })
    }else{
      this.setData({
        rate2:0,
        newSendLength:0,
        oldSendLength:0,
        sendValue:'',
        count2:0
      })
    }
  },

  setTimer(){
    var that=this
    app.globalData.timer=setInterval(() => {

      var rate= this.data.newValLength-this.data.oldValLength
      var rate2=this.data.newSendLength-this.data.oldSendLength

      this.setData({
        rate:rate,
        rate2:rate2,
        oldValLength:this.data.newValLength,
        oldSendLength:this.data.newSendLength,
      })
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  splitString(source, count){
    //  let str = "蚂蚁部落欢迎您蚂蚁部落欢，本站的url地址是www.softwhy.com";

      let arr = [];
      for (let i = 0, len = source.length / count; i < len; i++) {
        let subStr = source.substr(0, count);

        arr.push(subStr);
        source = source.replace(subStr, "");
        //  console.log(source,'source')
      }
      //  console.log(arr,'arr')
      return arr;

  },

// 写入数据
   handleSendvalue(buffer,flag,deviceId,serviceId,characteristicId,length){
    let that=this
    wx.writeBLECharacteristicValue({
      deviceId:  deviceId,
      serviceId:  serviceId,
      characteristicId: characteristicId,
      value: buffer,
      success: function (res) {
        if(flag!=3){//波特率
          if(flag==1){
            that.setData({
              currentBTL2:that.data.currentBTL,
              currentSJW2:that.data.currentSJW,
              currentTZW2:that.data.currentTZW,
              currentJYW2:that.data.currentJYW,
            })
            that.setData({
              modalName: null,
            })
          }else{
            var   checkStatus=that.data.checkedValue.indexOf('RTS')>=0?true:false
            that.setData({
              checkBtn2:that.data.checkBtn,
              checkedValue2:that.data.checkedValue,
              checkStatus:checkStatus
            })
          }
          wx.showToast({
            title: 'BleUart:串口设置成功',
            icon:"none",
            duration:1000
          })
          setTimeout(()=>{
            that.readBLECharacteristicValue(that._deviceId2, that._serviceId2, that._characteristicId2)
          },100)       
        }else  if(flag==3){//首页输入    
          var sendLength=that.data.newSendLength+length
          that.setData({
               newSendLength:sendLength,
              //  sendValue:''
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '发送失败',
          icon:"none",
          duration:1000
        })
        if(flag==2){//流控
          var checkBtn2=that.data.checkBtn2
          var   checkStatus=that.data.checkedValue2.indexOf('RTS')>=0?true:false
           checkBtn2.forEach(item => {
             if(that.data.checkedValue2.indexOf(item.value)>=0){
               item.checked=true
             }else{
               item.checked=false
             }
           });
          that.setData({
            openRTSBtn :that.data.flow=='开'?true:false,
            checkBtn:that.data.checkBtn2,
            checkedValue:that.data.checkedValue2,
            checkStatus:checkStatus
          })  
        }
      },
      complete:function(){
      }
    })
   },

  //  配置参数--Modem
   setValueModem(){
    //WCHBLEWxJsLib.setModemValue(this)
    WCHBLEWxJsLib.setModemValue(this.data.openRTSBtn , this.data.checkedValue  , this._deviceId2 , this._serviceId2 , this._characteristicId2 , this).then(res=>{
      wx.showToast({
        title: res.message,
        icon:"none",
      })
      console.log(res)
    }).catch(err=>{
      wx.showToast({
        title: err.message,
        icon:"none",
      })
      console.log(err)
    })
   },
// 设置波特率
   setValue(){
      WCHBLEWxJsLib.setBaudRateAndOptions(this.data.currentBTL,this.data.currentSJW,this.data.currentTZW,this.data.currentJYW,this._deviceId2,this._serviceId2,this._characteristicId2,this).then(res=>{
        wx.showToast({
          title: res.message,
          icon:'none'
        })
        console.log(res)
      }).catch(error=>{
        console.log(error)
      })
   },

  onShow: function () {
    this.setTimer()
  },

  chooseImg(){
    wx.chooseImage({
      success: function(res) {
        const tempFilePaths = res.tempFilePaths
        wx.saveFile({
          tempFilePath: tempFilePaths[0],
          success (res) {
            const savedFilePath = res.savedFilePath
          }
        })
      }
    })
    注意
  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    

  },

// 清除计时器
  clearInterval(){
    if(this.data.connected){
      this.setData({
        connected:false
      })
    }

    if(app.globalData.sendTimer){
      this.setData({
        sendFlag:true
      })
      clearInterval(app.globalData.sendTimer)
    }

    if(app.globalData.timer){
        clearInterval(app.globalData.timer)
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // console.log('onUload')
    this.clearInterval()
    },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})